/**********
    @name: 生成随机数 getRandomString
    @describtion: len: 长度
    @author:liubingye
    @date:2022-12-07 15:59:10
***********/
import {pinyin} from 'pinyin-pro'

const _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789';

function RandomIndex(min, max, i){
    let index = Math.floor(Math.random()*(max-min+1)+min),
        numStart = _charStr.length - 10;
    //如果字符串第一位是数字，则递归重新获取
    if(i==0&&index>=numStart){
        index = RandomIndex(min, max, i);
    }
    //返回最终索引值
    return index;
}
export function getRandomString(len){
    let min = 0, max = _charStr.length-1, _str = '';
    //判断是否指定长度，否则默认长度为15
    len = len || 15;
    //循环生成字符串
    for(var i = 0, index; i < len; i++){
        index = RandomIndex(min, max, i);
        _str += _charStr[index];
    }
    return _str;
}
// 将网络图片转换成base64格式
export function transBase64FromImage(image) {
    let canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    let ctx = canvas.getContext("2d");
    ctx.drawImage(image, 0, 0, image.width, image.height);
    // // 可选其他值 image/jpeg
    return canvas.toDataURL("image/png");
}
export function formatDate(value,args) {
    var dt = new Date(value);
    if(args == 'yyyy-M-d') {// yyyy-M-d
        let year = dt.getFullYear();
        let month = dt.getMonth() + 1;
        let date = dt.getDate();
        return `${year}-${month}-${date}`;
    } else if(args == 'yyyy-M-d H:m:s'){// yyyy-M-d H:m:s
        let year = dt.getFullYear();
        let month = dt.getMonth() + 1;
        let date = dt.getDate();
        let hour = dt.getHours();
        let minute = dt.getMinutes();
        let second = dt.getSeconds();
        return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
    } else if(args == 'yyyy-MM-dd') {// yyyy-MM-dd
        let year = dt.getFullYear();
        let month = (dt.getMonth() + 1).toString().padStart(2,'0');
        let date = dt.getDate().toString().padStart(2,'0');
        return `${year}-${month}-${date}`;
    } else {// yyyy-MM-dd HH:mm:ss
        let year = dt.getFullYear();
        let month = (dt.getMonth() + 1).toString().padStart(2,'0');
        let date = dt.getDate().toString().padStart(2,'0');
        let hour = dt.getHours().toString().padStart(2,'0');
        let minute = dt.getMinutes().toString().padStart(2,'0');
        let second = dt.getSeconds().toString().padStart(2,'0');
        return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
    }
}
export function blobToBase64(blobUrl) {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.onload = () => {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      canvas.width = img.width
      canvas.height = img.height
      ctx.drawImage(img, 0, 0)
      canvas.toBlob(blob => {
        const reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onloadend = () => resolve(reader.result)
        reader.onerror = reject
      }, 'image/png')
    }
    img.onerror = reject
    img.src = blobUrl
  })
}
export function base64toBlob(base64, type) {
    // 将base64转为Unicode规则编码
    let bstr = atob(base64, type),
        n = bstr.length,
        u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n) // 转换编码后才可以使用charCodeAt 找到Unicode编码
    }
    return new Blob([u8arr], {
        type
    })
}
// base64转file
export function base64toFile(base64Data, fileName, mimeType) {
  const byteCharacters = atob(base64Data.split(',')[1])
  const byteNumbers = new Array(byteCharacters.length)
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i)
  }
  const byteArray = new Uint8Array(byteNumbers)
  const file = new File([byteArray], fileName, { type: mimeType })
  return file
}
export function convertHexToBase64(hexString) {
    return btoa(hexString.match(/\w{2}/g).map(char => {
        return String.fromCharCode(parseInt(char, 16))
    }).join(''))
}
export function parseRtf(rtfData) {
    if (!rtfData) {
        return []
    }
    const regexPictureHeader = /{\\pict[\s\S]+?({\\\*\\blipuid\s?[\da-fA-F]+)[\s}]*/
    const regexPicture = new RegExp('(?:(' + regexPictureHeader.source + '))([\\da-fA-F\\s]+)\\}', 'g')
    const images = rtfData.match(regexPicture)
    const result = []

    if (images) {
        for (const image of images) {
            let imageType = false
            if (image.includes('\\pngblip')) {
                imageType = 'image/png'
            } else if (image.includes('\\jpegblip')) {
                imageType = 'image/jpeg'
            }
            if (imageType) {
                result.push({
                    hex: image.replace(regexPictureHeader, '').replace(/[^\da-fA-F]/g, ''),
                    type: imageType
                })
            }
        }
    }
    return result
}
// 防抖
export function myDebounce(fun, delay = 500) {
  let timer;
  return function () {
    let ctx = this
    let args = arguments
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      timer = null
      fun.apply(ctx, args)
    }, delay)
  }
}

// 节流
export function myThrottle(fun, interval = 500) {
  let last;
  let timer;
  return function () {
      let ctx = this
      let args = arguments
      let now = new Date()
      if (last && now - last < interval) {
        clearTimeout(timer)
        timer = setTimeout(function () {
          last = now
        }, interval)
      } else {
        last = now
        fun.apply(ctx, args)
      }
  }
}

// 秒数格式转换
export function formatTime(seconds, format) {
  let hours = Math.floor(seconds / 3600);
  let minutes = Math.floor((seconds % 3600) / 60);
  let remainingSeconds = seconds % 60;

  if (format === 'HH:mm:ss') {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  } else if (format === 'mm:ss') {
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  } else {
    return 'Invalid format';
  }
}

// 近段时间获取，返回时间对象
export function getStartAndEndTimes(type,timeStamp=false) {
  const now = new Date();
  let startTime, endTime;
  const dayOfWeek = now.getDay(); // 获取当前日期是本周的第几天
  const startOfWeek = now.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1); // 获取本周的第一天
  const endOfWeek = startOfWeek + 6; // 获取本周的最后一天
  const currentQuarter = Math.floor((now.getMonth() / 3));

  switch (type) {
    case 0:
      startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
      endTime = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0);
      break;
    case 1:
      startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, 0, 0, 0);
      endTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
      break;
    case 2:
      startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 6, 0, 0, 0);
      endTime = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0);
      break;
    case 3:
      startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 29, 0, 0, 0);
      endTime = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0);
      break;
    case 4:
      startTime = new Date(now.getFullYear(), now.getMonth() - 2, now.getDate(), 0, 0, 0);
      endTime = new Date(now.getFullYear(), now.getMonth() + 1, now.getDate() + 1, 0, 0, 0);
      break;
    case 5:
      startTime = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate(), 0, 0, 0);
      endTime = new Date(now.getFullYear(), now.getMonth() + 1, now.getDate() + 1, 0, 0, 0);
      break;
    case 6:
      startTime = '';
      endTime = '';
      break;
    case 7:
      //本周
      startTime = new Date(now.getFullYear(), now.getMonth(), startOfWeek, 0, 0, 0);
      endTime = new Date(now.getFullYear(), now.getMonth(), endOfWeek, 0, 0, 0);
      break;
    case 8:
      //本月
      startTime = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0);
      endTime = new Date(now.getFullYear(), now.getMonth() + 1, 1, 0, 0, 0);
      break;
    case 9:
      //本季度
      startTime = new Date(now.getFullYear(), currentQuarter * 3, 1, 0, 0, 0);
      endTime = new Date(now.getFullYear(), (currentQuarter + 1) * 3, 1, 0, 0, 0);
      break;
    case 10:
      //本年度
      startTime = new Date(now.getFullYear(), 0, 1, 0, 0, 0);
      endTime = new Date(now.getFullYear() + 1, 0, 1, 0, 0, 0);
      break;
    default:
      throw new Error('Invalid option');
  }
  if(timeStamp){
    return {
      startTime: startTime.getTime(),
      endTime: endTime.getTime()
    }
  }else{
    return [startTime, endTime];
  }
}

// 时间差判断
export function getTimeDifference(startTime, endTime) {
  if (!startTime || !endTime) {
    return null; // 如果开始时间或结束时间为空，返回null
  }

  const oneDay = 24 * 60 * 60 * 1000; // 1天的毫秒数
  const oneWeek = 7 * oneDay; // 1周的毫秒数
  const oneMonth = 30 * oneDay; // 1月的毫秒数
  const oneYear = 365 * oneDay; // 1年的毫秒数

  const startDate = new Date(startTime);
  const endDate = new Date(endTime);

  // 计算两个时间之间的差异
  const timeDifference = Math.abs(endDate - startDate);

  if (timeDifference <= oneDay) {
    return 0; // 小于1天，返回0
  } else if (timeDifference <= oneWeek) {
    return 1; // 1-7天，返回1
  } else if (timeDifference <= oneMonth) {
    return 2; // 7天-1个月，返回2
  } else if (timeDifference <= 3 * oneMonth){
    return 3; //1个月-3个月，返回3
  }else if (timeDifference <= oneYear) {
    return 4; // 3个月-1年，返回4
  } else if (timeDifference < 2 * oneYear) {
    return 5; // 1年-2年，返回5
  } else {
    return 6; // 大于2年，返回6
  }
}
//根据十六进制颜色转换
export function applyOpacityArray(hexColor, opacityArray) {
  // 将十六进制颜色转换为 RGB 值
  let r = parseInt(hexColor.slice(1, 3), 16);
  let g = parseInt(hexColor.slice(3, 5), 16);
  let b = parseInt(hexColor.slice(5, 7), 16);
  let colors = [];
  opacityArray.forEach(item => {
    // 将透明度转换为 0-1 之间的小数
    let alpha =  Math.round(item * 255);
    // 计算带有透明度的 RGB 值
    let newR = Math.round((r * alpha + (255 - alpha) * 255) / 255);
    let newG = Math.round((g * alpha + (255 - alpha) * 255) / 255);
    let newB = Math.round((b * alpha + (255 - alpha) * 255) / 255);
    // 构建带有透明度的十六进制颜色
    var newHexColor = '#' + newR.toString(16) + newG.toString(16) + newB.toString(16);
    colors.push(newHexColor);
  })
  return colors;
}
/**
 * 计算文件大小
 * @return {number}                   文件大小（字节）
 */
export function size2Str(size) {
  if (size < 1024) {
    return size + 'B';
  }else if(size >= 1024 && size < Math.pow(1024, 2)){
    return parseFloat(size / 1024).toFixed(2) + 'KB';
  }else if(size >= Math.pow(1024, 2) && size < Math.pow(1024, 3)){
    return parseFloat(size / Math.pow(1024, 2)).toFixed(2) + 'MB';
  }else if(size > Math.pow(1024, 3)){
    return parseFloat(size / Math.pow(1024, 3)).toFixed(2) + 'GB';
  }else {
    return 0 + 'B';
  }
}
// 通用下载
export function download(url, fileName) {
  fetch(url)
    .then(response => response.blob())
    .then(blob => {
      const link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = fileName || 'download';
      link.click();
      window.URL.revokeObjectURL(link.href);
    })
    .catch(error => console.error('下载文件时出错:', error));
}

// 通用方法，创建映射
export function createMapping(array, { keyProp = 'value', valueProp = 'label' } = {}) {
  const mapping = array.reduce((acc, item) => {
    acc[item[keyProp]] = item[valueProp]
    return acc
  }, {})
  return mapping
}

// json字符串格式化
export function jsonFormat(jsonStr) {
  try {
    if(!jsonStr) return
    var jsonObj = JSON.parse(jsonStr)
    // 设置缩进为 4 个空格
    var formattedJson = JSON.stringify(jsonObj, null, 4)
    // 换行符 '\n' 替换为 '\r\n'
    formattedJson = formattedJson.replace(/\n/g, '\r\n')
    return formattedJson
  } catch (error) {
    return
  }
}

// 根据图片file获取图片宽高属性
export async function getImageSize(file, maxWidth) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      const img = new Image()
      img.onload = () => {
        let scale = 1
        let width = img.width
        let height = img.height
        // 如果图片宽度大于 maxWidth，进行缩放
        if (width > maxWidth) {
          scale = maxWidth / width
          width = maxWidth
          height = Math.round(height * scale)
        }
        console.log('图片宽度:', img.width)
        console.log('图片高度:', img.height)
        resolve({ width, height, scale })
      }
      img.onerror = (error) => {
        console.error('图片加载失败:', error)
        reject(error)
      };
      img.src = e.target.result
    }
    reader.readAsDataURL(file)
  })
}
// 随机名称生成
export function generateCustomString(prefix, input) {
  function generateRandomContent(length = 6) {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      let result = ''
      for (let i = 0; i < length; i++) {
          const randomIndex = Math.floor(Math.random() * chars.length)
          result += chars[randomIndex]
      }
      return result
  }

  // 判断是否为中文
  const isChinese = /[\u4e00-\u9fa5]/.test(input)
  let name
  if (isChinese) {
      // 取汉字的拼音首字母
      name = pinyin(input, { pattern: 'first', type: 'array' }).flat().join('')
  } else {
      name = input
  }
  // 生成随机内容
  const randomContent = generateRandomContent()
  const result = `${prefix}_${name}_${randomContent}`
  return result
}
// uuid生成
export function generateUUID() {
  return 'xxxxxxxx_xxxx_4xxx_yxxx_xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0,
        v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}

// 梯度颜色生成
export function generateColorGradient(startColor, steps=6) {
  // 将十六进制颜色转换为RGB数组
  function hexToRgb(hex) {
    let r = parseInt(hex.slice(1, 3), 16);
    let g = parseInt(hex.slice(3, 5), 16);
    let b = parseInt(hex.slice(5, 7), 16);
    return [r, g, b];
  }

  // 将RGB数组转换回十六进制颜色
  function rgbToHex(r, g, b) {
    return `#${[r, g, b].map(x => x.toString(16).padStart(2, '0')).join('')}`;
  }

  // 获取起始颜色的RGB值
  let startRGB = hexToRgb(startColor);

  // 计算每一步的颜色变化量（调整为让颜色变浅，即各通道值递增）
  let totalRChange = (255 - startRGB[0]) / (steps - 1); // 朝着255变化，让红色通道值增加变浅
  let totalGChange = (255 - startRGB[1]) / (steps - 1); // 朝着255变化，让绿色通道值增加变浅
  let totalBChange = (255 - startRGB[2]) / (steps - 1); // 朝着255变化，让蓝色通道值增加变浅

  // 生成颜色梯度数组
  let colorGradient = [];
  for (let i = 0; i < steps; i++) {
    let r = Math.round(startRGB[0] + totalRChange * i);
    let g = Math.round(startRGB[1] + totalGChange * i);
    let b = Math.round(startRGB[2] + totalBChange * i);
    colorGradient.push(rgbToHex(r, g, b));
  }

  return colorGradient;
}

// px转rem
export function pxToRem(pxValue) {
  const remValue = parseFloat(pxValue / 100).toFixed(2)
  return remValue + 'rem'
}

// 判断输入值是否为数字+px结尾，或者数字+%结尾，或者数字+vw,数字+vh。不是则提示输入格式有误且返回false，以%结尾的话返回%，以vw结尾返回vw，以vh结尾返回vh，否则返回px
export function checkValue(inputValue) {
  const regexPx = /^\d+px$/
  const regexPercent = /^\d+%$/
  const regexVw = /^\d+vw$/
  const regexVh = /^\d+vh$/

  if (regexPx.test(inputValue)) {
    return 'px'
  } else if (regexPercent.test(inputValue)) {
    return '%'
  } else if (regexVw.test(inputValue)) {
    return 'vw'
  } else if (regexVh.test(inputValue)) {
    return 'vh'
  } else {
    return false
  }
}
